﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PressureTest
{
    public partial class ManageFormPoint : Form
    {
        /// <summary>模型
        /// 
        /// </summary>
        private FormPoint obj = new FormPoint();

        /// <summary>DataGridView
        /// 
        /// </summary>
        private DataGridView dataGridView;

        /// <summary>设备点位列表
        /// 
        /// </summary>
        DataTable devicePointTable = new DataTable();

        /// <summary>设备点位编码
        /// 
        /// </summary>
        string selectedDevicePointNumber;

        /// <summary>刷新界面
        /// 
        /// </summary>
        private void FreshForm()
        {
            NumberTextBox.Text = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
            FormPointNameTextBox.Text = "";
            PointComboDataGridView.Text = "";
            obj = new FormPoint();
        }

        /// <summary>重复检测
        /// 
        /// </summary>
        /// <returns></returns>
        private bool CheckRepeat()
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["name"] = FormPointNameTextBox.Text;
            List<FormPoint> list = SqlSugarHelper.Inquireable<FormPoint>(where);
            int count = list.Count;
            if (count > 0)
            {
                Alert.Error(where["name"] + "点位已存在");
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>界面点位列表
        /// 
        /// </summary>
        public void LoadFormPointList()
        {
            List<FormPoint> list = SqlSugarHelper.Inquireable<FormPoint>(null);
            UpdateDataGridViewRow(list);
        }

        /// <summary>更新DataGridView
        /// 
        /// </summary>
        /// <param name="list"></param>
        private void UpdateDataGridViewRow(List<FormPoint> list)
        {
            if (dataGridView.Rows.Count > 1)
            {
                this.Invoke(new Action(() =>
                {
                    dataGridView.Rows.Clear();
                }));
            }

            foreach (FormPoint item in list)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.Add(dataGridViewBoxCell(item.number.ToString()));
                row.Cells.Add(dataGridViewBoxCell(item.name));
                row.Cells.Add(dataGridViewBoxCell(item.device_point_number.ToString()));
                row.Cells.Add(dataGridViewBoxCell(item.device_point_name));
                row.Height = 40;
                this.Invoke(new Action(() =>
                {
                    dataGridView.Rows.Add(row);
                }));
            }
            this.HideWaitForm();
        }

        // <summary> 创建DataGridViewTextBoxCell
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private DataGridViewTextBoxCell dataGridViewBoxCell(string str)
        {
            DataGridViewTextBoxCell cell1 = new DataGridViewTextBoxCell();
            cell1.Value = str;
            return cell1;
        }

        /// <summary>设备点位
        /// 
        /// </summary>
        public void LoadDevicePointList()
        {
            List<DevicePoint> list = SqlSugarHelper.Inquireable<DevicePoint>(null);
            foreach (DevicePoint item in list)
            {
                this.Invoke(new Action(() =>
                {
                    devicePointTable.Rows.Add(item.point_number.ToString(), item.point_name);
                }));
            }
        }

        /// <summary>更新obj
        /// 
        /// </summary>
        /// <returns></returns>
        private FormPoint UpdateObj()
        {
            obj.number = NumberTextBox.Text.ToInt();
            obj.name = FormPointNameTextBox.Text;
            obj.device_point_number = selectedDevicePointNumber.ToInt();
            obj.device_point_name = PointComboDataGridView.Text;
            return obj;
        }

        public ManageFormPoint()
        {
            InitializeComponent();
            this.dataGridView = this.FormPointDataGridView;
            devicePointTable.Columns.Add("number", typeof(string));
            devicePointTable.Columns.Add("name", typeof(string));
            PointComboDataGridView.DataGridView.Init();
            PointComboDataGridView.ItemSize = new System.Drawing.Size(280, 400);
            PointComboDataGridView.DataGridView.AddColumn("点位编号", "number");
            PointComboDataGridView.DataGridView.AddColumn("点位名称", "name");
            PointComboDataGridView.ShowFilter = true;
            PointComboDataGridView.DataGridView.DataSource = devicePointTable;
            PointComboDataGridView.FilterColumnName = "number;name";
        }

        /// <summary>操作成功
        /// 
        /// </summary>
        private void OperationSuccess()
        {
            Task.Run(() =>
            {
                LoadFormPointList();
            });
            FreshForm();
        }

        private void FormPoint_Load(object sender, EventArgs e)
        {
            this.ShowWaitForm("加载界面点位");
            OperationSuccess();
            Task.Run(() =>
            {
                LoadDevicePointList();
            });
        }

        private void PointComboDataGridView_ValueChanged(object sender, object value)
        {
            DataGridViewRow row = (DataGridViewRow)value;
            PointComboDataGridView.Text = row.Cells["点位名称"].Value.ToString();//通过ColumnName显示值
            selectedDevicePointNumber = row.Cells["点位编号"].Value.ToString();
        }

        private void confirmButton_Click(object sender, EventArgs e)
        {
            if (FormPointNameTextBox.Text.IsNullOrEmpty())
            {
                Alert.Error("请输入界面点位名称");
                return;
            }

            if (PointComboDataGridView.Text.IsNullOrEmpty())
            {
                Alert.Error("请选择要绑定的点位");
                return;
            }

            if (obj.number > 0)
            {
                if (obj.name != FormPointNameTextBox.Text)
                {
                    bool repeatRes = CheckRepeat();
                    if (repeatRes)
                    {
                        return;
                    }
                }
                UpdateObj();
                List<FormPoint> list = new List<FormPoint>();
                list.Add(obj);
                int res = SqlSugarHelper.Updateable<FormPoint>(list);
                if (res > 0)
                {
                    OperationSuccess();
                }
                else
                {
                    Alert.Error("编辑界面点位失败");
                }
            }
            else
            {
                bool repeatRes = CheckRepeat();
                if (repeatRes)
                {
                    return;
                }
                UpdateObj();
                List<FormPoint> list = new List<FormPoint>();
                list.Add(obj);
                int res = SqlSugarHelper.Insertable(list);
                if (res > 0)
                {
                    OperationSuccess();
                }
                else
                {
                    Alert.Error("添加界面点位失败");
                }
            }
        }

        private void EditMenu_Click(object sender, EventArgs e)
        {
            bool res = CheckSelectedRowExist();
            if (!res)
            {
                return;
            }
            NumberTextBox.Text = obj.number.ToString();
            FormPointNameTextBox.Text = obj.name;
            PointComboDataGridView.Text = obj.device_point_name;
            selectedDevicePointNumber = obj.device_point_number.ToString();
        }

        private void DeleteMenu_Click(object sender, EventArgs e)
        {
            bool res = CheckSelectedRowExist();
            if (!res)
            {
                return;
            }
            res = this.ShowAskDialog2("友情提示", "您确定要删除吗?", true);
            if (res)
            {
                List<FormPoint> list = new List<FormPoint>();
                list.Add(obj);
                int deleteRes = SqlSugarHelper.Deleteable(list);
                if (deleteRes > 0)
                {
                    OperationSuccess();
                }
            }
        }

        /// <summary>判断记录是否存在
        /// 
        /// </summary>
        /// <param name="number"></param>
        private bool CheckSelectedRowExist()
        {
            int number = SelectedRowPrimaryKey();
            obj = RowWithNumber(number);
            if (obj == null)
            {
                Alert.Error("记录不存在");
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>选中记录主键值
        /// 
        /// </summary>
        /// <returns></returns>
        private int SelectedRowPrimaryKey()
        {
            int index = this.dataGridView.CurrentRow.Index;
            return this.dataGridView.Rows[index].Cells[0].Value.ToString().ToInt();
        }

        /// <summary>根据名称查询记录
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private FormPoint RowWithNumber(int number)
        {
            Dictionary<string, object> where = new Dictionary<string, object>();
            where["number"] = number.ToString();
            List<FormPoint> list = SqlSugarHelper.Inquireable<FormPoint>(where);
            if (list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return null;
            }
        }


        /// <summary>双击某条记录
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormPointDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView.ClearSelection();
            dataGridView.Rows[e.RowIndex].Selected = true;
            dataGridView.CurrentCell = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
            OperationMenu.Show(MousePosition.X, MousePosition.Y);
        }
    }
}
